package zgame.main;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import zgame.bean.Port;
import zgame.socket.DataPackage;
import zgame.socket.DataReceiveListener;
import zgame.socket.handle.ClientRequestHandle;
import zgame.socket.server.ServerConnection;
import zgame.utils.Control;

public class ServerListener extends Control {
  private static final Logger log = Logger.getLogger(ServerListener.class);
  private static boolean isRunning = true;
  
  @Override
  public void perform() {
    ServerSocket servSock = null;
    try {
      Port playGamePort = Global.currentServiceInfo.getPort(Constants.CHAT_PORT_NAME);
      
      servSock = new ServerSocket(playGamePort.getValue());
      log.info("-------------------------------------------------------");
      log.info("GAME SERVER " + Global.currentServiceInfo.getName() + " WAS STARTED AT PORT " + playGamePort.getValue());
      log.info("-------------------------------------------------------");
    } catch (IOException e) {
      log.error("Server can't start.Please check your config file");
      return;
    }

    // Listening
    while (isRunning) {
      try {
        Socket clientSocket = servSock.accept();
        ServerConnection connection = new ServerConnection(clientSocket);
        new AddRequestToPoolListener().setServerConnection(connection);
        Global.notAuthenConnectionList.add(connection);
      } catch (IOException e) {
        log.warn("Exception on accept client", e);
      }
    }
  }

  public void cancel() {
    isRunning = false;
  }
  
  static class AddRequestToPoolListener implements DataReceiveListener {
    private ServerConnection serverConnection;
    
    public void setServerConnection(ServerConnection serverConnection) {
      this.serverConnection = serverConnection;
      if (serverConnection != null) {
        serverConnection.setListener(this);  
      }
    }

    @Override
    public void onConnectDone() {
    }

    @Override
    public void onConnectFail() {
    }

    @Override
    public void onDisconnect() {
    }

    @Override
    public void onRecieveData(DataPackage dataPackage) {
      RequestManager.instance().addRequest(new ClientRequestHandle(serverConnection, dataPackage));
    }
  }
}
